<?php
$loader->requireOnce('ordo/Service.class.php');
$loader->requireOnce('includes/Utils.class.php');
$loader->requireOnce('includes/AjaxRender/TicketRender.class.php');
$loader->requireOnce('includes/LabConnector/LabAdminConnector.class.php');
$loader->requireOnce('includes/RadConnector/RadAdminConnector.class.php');

$loader->requireOnce('includes/CoreErrorCode.class.php');
$loader->requireOnce('includes/CoreException.class.php');

class C_Service extends Controller {

	var $template_mod;

	function __construct($template_mod = "general") {
		parent::Controller();
		$this->setLayout('admin');
		$this->template_mod = $template_mod;
		$this->view->path = 'service';
	}

	public function actionFilterRoomAjax() {
		$servId = $_GET['service_id'];
		$room = Celini::newORDO('Room');
		$result = $room->fromService($servId);
		$responseText = "";
		foreach ($result as $key=>$value) {
			$responseText .= "<option value=\"$key\">$value</option>";
		}
		return $responseText;
	}

	public function actionManagement() {
		return $this->view->render('management.html');
	}

	public function actionGetPatientPriceAjax() {
		$serviceId = $_GET['service_id'];
		$ticketId = $_GET['ticket_id'];
		$s = Celini::newORDO('Service', $serviceId);
		$t = Celini::newORDO('Ticket', $ticketId);
		$promotionProgram = $t->get('sale_program_store_id');
		if (!empty($promotionProgram)) {
			return L10nHelper::renderCurrency($s->get('price'));
		} else {
			$insuranceType = $t->get('insurance');
			if ($insuranceType == Insurance::REQUIRED) {
				return L10nHelper::renderCurrency($s->get('patient_required_insurance_price'));
			} else if ($insuranceType == Insurance::VOLUNTEERED) {
				return L10nHelper::renderCurrency($s->get('patient_volunteered_insurance_price'));
			} else {
				return L10nHelper::renderCurrency($s->get('price'));
			}
		}
	}

	public function actionList() {
		$serviceGroupList = Celini::newORDO('ServiceGroup')->getListAllForCombo();
		$this->assign('serviceGroupList', $serviceGroupList);
		return $this->view->render('service_list.html');
	}

	public function actionEdit() {
		$serviceId = $_GET['service_id'];
		$serv = Celini::newORDO('Service');
		$roomArr = array();
		if (isset($_GET['service_id']) && $_GET['service_id'] != "") {
			$serv->setup($serviceId);
		}

		$this->assign_by_ref('service', $serv);
		return $this->view->render('edit_service.html');
	}
	
	public function actionListServiceAjax() {
		$serviceGroupId = $_GET['serviceGroupId'];
		$disabled = $_GET['disabled'];
		if ($serviceGroupId == 'Others') {
			$serviceGroupId = false;
		}
		if ($disabled == 'all') {
			$disabled = false;
		}
		$servList = Celini::newORDO('Service')->getServiceInfo($serviceGroupId, $disabled);
		return json_encode($this->renderServiceList($servList));
	}

	public function actionChangeServiceStatusAjax() {
		$serviceId = $_GET['service_id'];
		$serv = Celini::newORDO('Service', $serviceId);
		$status = $serv->get('disabled');

		if ($status == 0) {
			$newStatus = 1;
		} else if ($status == 1) {
			$newStatus = 0;
		}

		$serv->set('disabled', $newStatus);
		$serv->persist();
	}
	
	public function actionCheckDuplicate(){
		$code = trim($_POST['code']);
		$name = Utils::sanitizeText($_POST['service_name']);
		$id	= $_POST['service_id'];
		$serv = Celini::newORDO('Service');
		return $serv->checkDuplicate($code, $name, $id);
	}
	
	public function actionSaveServiceAjax() {
		$data = array (
			'item_type' 							=> 	"service",
			'code'									=>	trim($_POST['code']),
			'disabled'								=> 	$_POST['disabled'],
			'price'									=> 	$_POST['price'],
		 	'insurance_price'						=>	$_POST['insurance_price'],
		 	);

		$serv = Celini::newORDO('Service');
		if (isset($_POST['service_id']) && $_POST['service_id'] != "") {
			$serv->setup(trim($_POST['service_id']));
		}
		$id	=	$serv->get_id();
		$name			=	Utils::sanitizeText($_POST['service_name']);
		if($id > 0){
			$field			=	L10nHelper::changeField(L10nHelper::getLocale(),"name");
			$data[$field]	=	$name;
		}
		// Service has no name, add new localized name
		else{
			$supported	=	L10nHelper::getSupportedLocales();
			foreach ($supported as $locale	=>	$country){
				$locale			=	L10nHelper::changeField($locale,"name");
				$data[$locale]	=	$name;
			}
		}
		$serv->populateArray($data);
		$serv->persist();
		$servId = $serv->get_id();
		
		return $servId;
	}
	/**
	 * Load lab addmin module.
	 * @author hdviet
	 *
	 * @return html
	 */
	public function actionLabManagement() {
	    $logger = LoggerManager::getLogger('local.controllers.C_Service');
		//return $this->view->render('test_management.html');
		$result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');

        $logger->info('Start actionLabManagement');
       try {

            $labAdminConnector = new LabAdminConnector();
            $result['result'] = $labAdminConnector->renderAdminPage();

        } catch (HISFileLoaderException $hisEx) {
            $result['error']['code'] = CoreErrorCode::LOAD_LAB_MODULE_FAIL;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::LOAD_LAB_MODULE_FAIL);
            $logger->error('actionLabManagement fail. Error detail: '. $hisEx->getMessage());


        } catch (EnumException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = CoreErrorCode::getErrorMess($ex->getErrorCode());
            $logger->error('actionLabManagement fail. Error detail: '. $ex->getMessage());
        }

        if ($result['error']['code'] != CoreErrorCode::NORMAL) {
            return $result['error']['mess'];
        }

        $logger->info('Finish actionLabManagement');
        return $result['result'];

	}

	public function actionListTest() {
		$testList = Celini::newORDO('Test')->listAllFullInfo();
		$this->assign('testList', $testList);
		return $this->view->render('test_list.html');
	}

	public function actionListTestItem() {
		return $this->view->render('test_item_list.html');
	}

	public function actionListTestItemAjax() {
		$testList = Celini::newORDO('Service')->getTestItemInfo();
		return json_encode($this->renderTestItemList($testList));
	}

	public function actionEditTestItem() {
		$serviceId = $_GET['service_id'];
		$testItem = Celini::newORDO('Service');
		$testGroupList = Celini::newORDO('Test')->listAll();
		$selectedTestGroup = '';
		if (isset($_GET['service_id']) && $_GET['service_id'] != "") {
			$testItem->setup($serviceId);
			$selectedTestGroup = Celini::newORDO('TestService')->getTestGroupOfItem($serviceId);
		}
		$this->assign_by_ref('testGroupList', $testGroupList);
		$this->assign_by_ref('testItem', $testItem);
		$this->assign('selectedTestGroup', $selectedTestGroup);

		return $this->view->render('edit_test_item.html');
	}

	public function actionSaveTestItemAjax() {
		$data = array (
			'item_type' 		=>	"test",
			'disabled'			=>	$_POST['disabled'],
			'serviceGroupId'		=>	0,
			'payment_type'		=>	'after',
			'price'									=>	L10nHelper::getNumber($_POST['price']),
		 	'required_insurance_price'				=>	L10nHelper::getNumber($_POST['required_insurance_price']),
			'volunteered_insurance_price'			=>	L10nHelper::getNumber($_POST['volunteered_insurance_price']),
			'patient_required_insurance_price'		=>	L10nHelper::getNumber($_POST['patient_required_insurance_price']),
			'patient_volunteered_insurance_price'	=>	L10nHelper::getNumber($_POST['patient_volunteered_insurance_price'])
		 	);

		$serv = Celini::newORDO('Service');
		if (isset($_POST['service_id']) && $_POST['service_id'] != "") {
			$serv->setup(trim($_POST['service_id']));
		}

		$id			=	$serv->get_id();
		$name		=	Utils::sanitizeText($_POST['service_name']);
		$data		=	array();
		if($id > 0){
			$field		=	L10nHelper::changeField(L10nHelper::getLocale(),"name");
			$data[$field]	=	$name;
		}
		// Service has no name, add new localized name
		else{
			$supported	=	L10nHelper::getSupportedLocales();
			foreach ($supported as $locale	=>	$country){
				$locale		=	L10nHelper::changeField($locale,"name");
				$data[$locale]	=	$name;
			}
		}

		$serv->populateArray($data);
		$serv->persist();
		$servId = $serv->get_id();

		$testService = Celini::newORDO('TestService');
		$testServiceId = $testService->getTestServiceId($servId);
		$testData = '';
		if ($testServiceId == 0) {
			$testData = array (
				'test_id'		=>	$_POST['testService'],
				'service_id'	=>	$servId
			);
		} else {
			$testData = array (
				'test_service_id' 	=>	$testServiceId,
				'test_id' 			=>	$_POST['testService'],
				'service_id' 		=>	$servId
			);
		}
		$testService->populateArray($testData);
		$testService->persist();
		return $servId;
	}

	/**
	 * Create a new group test or modify a specified group test.
	 *
	 */
	public function actionEditTest() {
		$groupTestId = $_GET['service_id'];
        $groupTest = Celini::newORDO('Test');
        $roomList = Celini::newORDO('Room')->listRooms();
        if (isset($groupTestId) && $groupTestId != "") {
            $groupTest->setup($groupTestId);
        }
        $this->assign_by_ref('groupTest', $groupTest);
        $this->assign_by_ref('roomList', $roomList);

        return $this->view->render('edit_group_test.html');
	}

	/**
	 * Save the group test.
	 *
	 */
	public function actionSaveGroupTestAjax() {
		$data = array (
			'room_id' 		=> 	$_POST['room'],
			'payment_type' 	=> 	$_POST['payment_type'],
		);
		$groupTest = Celini::newORDO('Test');
		if (isset($_POST['group_test_id']) && $_POST['group_test_id'] != "") {
			$groupTest->setup($_POST['group_test_id']);
		}
		$name		=	Utils::sanitizeText($_POST['group_test_name']);
       	$id	=	$groupTest->get_id();
		if($id > 0){
			$field		=	L10nHelper::changeField(L10nHelper::getLocale(),"name");
			$data[$field]	=	$name;
		}
		// Test has no name, add new localized name
		else{
			$supported	=	L10nHelper::getSupportedLocales();
			foreach ($supported as $locale	=>	$country){
				$locale		=	L10nHelper::changeField($locale,"name");
				$data[$locale]	=	$name;
			}
		}
		$groupTest->populateArray($data);
		$groupTest->persist();

		return $groupTest->get_id();
	}

	/**
	 * Change the status ('disabled', 'enabled') of group test.
	 *
	 */
    public function actionChangeGroupTestStatusAjax() {
    	$testId = $_GET['test_id'];
    	$test = Celini::newORDO('Test', $testId);
    	$status = $test->get('disabled');

        if ($status == 0) {
            $newStatus = 1;
        } else if ($status == 1) {
            $newStatus = 0;
        }
        $test->set('disabled', $newStatus);
        $test->persist();
    }

	private function renderServiceList($servList) {
		$sr = Celini::newORDO('ServiceRoom');
		$body = "";
		$count = 1;
		foreach ($servList as $row) {
			$id = $row['service_id'];
			$aRow = "";
			$aRow .= "<tr id=$id>";
			$aRow .= "<td><span class=\"order\">$count</span></td>";
			$aRow .= "<td><a href=\"javascript:editService($id);\" title=\"" . L10nHelper::_("Edit service") . "\">" . $row['name'] . "</a></td>";
			$aRow .= "<td>" . $row['code']. "</td>";
			$aRow .= "<td>" . L10nHelper::renderCurrency($row['price']) . "</td>";
			$aRow .= "<td>" . L10nHelper::renderCurrency($row['insurance_price']) . "</td>";
			if ($row['disabled'] == 0) {
				$aRow .= "<td><span>" . L10nHelper::_("In Use_1") . "</span></td>";
				$aRow .= "<td><a class=\"btn\" href=\"javascript:lockService($id);\" title=\"" . L10nHelper::_("Service temporary locked") . "\">"
				. "<img src=\"../images/lock_small.png\" alt=\"" . L10nHelper::_("Lock") . "\"></img>"
				. "</a></td>";
			} else if ($row['disabled'] == 1) {
				$aRow .= '<td><span class="impression">Lock</span></td>';
				$aRow .= "<td><a class=\"btn\" href=\"javascript:unlockService($id);\" title=\"" . L10nHelper::_("Reuse service") . "\">"
				. "<img src=\"../images/unlock_small.png\" alt=\"" . L10nHelper::_("Reuse") . "\"></img>"
				. "</a></td>";
			}
			$aRow .= "</tr>";
			$body .= $aRow;
			$count++;
		}
		$total = '<table class="grid" cellspacing="0" cellpadding="0" width="780px">';
		$total .= '<tr><td class="first last">' . L10nHelper::_('Total : <span id="total">%s</span>',--$count).'</td></tr>';
		$total .= '</table>';
		return array('body' => $body, 'total' => $total);
	}

	private function renderTestItemList($testList) {
		$sr = Celini::newORDO('ServiceRoom');
		$body = "";
		$count = 1;
		foreach ($testList as $row) {
			$aRow = "";
			$room = "";

			$id = $row['service_id'];
			$res = $sr->getRoomsOfService($id);
			foreach ($res as $roomName) {
				$room .= $roomName['name'] . ", ";
			}

			if (strlen($room) > 0) {
				$room = substr($room, 0, strlen($room) - 2);
			}

			$payment = L10nHelper::_("Postpaid");
			if ($row['payment_type'] == Service::BEFORE) {
				$payment = L10nHelper::_("Prepaid");
			}

			$aRow .= "<tr id=\"$id\">";
			$aRow .= "<td><span class=\"order\">$count</span></td>";
			$aRow .= "<td><a href=\"javascript:editTestItem($id);\" title=\"" . L10nHelper::_("Edit service") . "\">" . $row['name'] . "</a></td>";
			$aRow .= "<td>$room</td>";
			$aRow .= "<td>" . L10nHelper::renderCurrency($row['price']) . "</td>";
//			$aRow .= "<td>" . L10nHelper::renderCurrency($row['patient_required_insurance_price']) . "</td>";
//			$aRow .= "<td>" . L10nHelper::renderCurrency($row['patient_volunteered_insurance_price']) . "</td>";
			$aRow .= "<td>" . $payment . "</td>";
			if ($row['disabled'] == 0) {
				$aRow .= "<td><span>" . L10nHelper::_("In Use_1") . "</span></td>";
				$aRow .= "<td><a class=\"btn\" href=\"javascript:lockService($id);\" title=\"" . L10nHelper::_("Service temporary locked") . "\">"
				. "<img src=\"../images/lock_small.png\" alt=\"" . L10nHelper::_("Lock") . "\"></img>"
				. "</a></td>";
			} else if ($row['disabled'] == 1) {
				$aRow .= '<td><span class="impression">' . L10nHelper::_("Lock") . '</span></td>';
				$aRow .= "<td><a class=\"btn\" href=\"javascript:unlockService($id);\" title=\"" . L10nHelper::_("Reuse service") . "\">"
				. "<img src=\"../images/unlock_small.png\" alt=\"" . L10nHelper::_("Reuse") . "\"></img>"
				. "</a></td>";
			}
			$aRow .= "</tr>";
			$body .= $aRow;
			$count++;
		}
		$total = '<table class="grid" cellspacing="0" cellpadding="0" width="780px">';
		$total .= '<tr><td class="first last">' . L10nHelper::_('Total : <span id="total">%s</span>',--$count).'</td></tr>';
		$total .= '</table>';
		return array('body' => $body, 'total' => $total);
	}

	public function actionRadManagement() {
        $logger = LoggerManager::getLogger('local.controllers.C_Service');
        $result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );

       $logger->info('Start action RadManagement');
       try {
            $connector = new RadAdminConnector();
            $result['result'] = $connector->renderAdminPage();

        } catch (HISFileLoaderException $hisEx) {
            $result['error']['code'] = CoreErrorCode::LOAD_RAD_MODULE_FAIL;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::LOAD_RAD_MODULE_FAIL);
            $logger->error('Action RadManagement fail. Error message: '. $hisEx->getMessage());

        } catch (Exception  $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = CoreErrorCode::getErrorMess($ex->getErrorCode());
            $logger->error('Action RadManagement fail. Error message: '. $ex->getMessage());
        }

        if ($result['error']['code'] != CoreErrorCode::NORMAL) {
            return $result['error']['mess'];
        }

        $logger->info('Finish action RadManagement');

        return $result['result'];

	}
	
    /**
     * Get services by code.
     *
     */
	function actionGetServiceCodeAutocompleteAjax() {
        $q = $_GET['q'];
        if (!$q) return;
        $q = strtoupper($q);
        $result = Celini::newORDO('Service')->getServiceAutoCompleteByCode($q);
        foreach ($result as $item) {
            $price = L10nHelper::renderNumber($item['price'], 0);
             echo $item['code'] . '|' . $item['name'] . '|' . $item['service_id'] . '|' . $price . '|' . $item['price'] . "\n";
        }
    }
}
?>